package com.rc.evcharger.service.elec;

import com.rc.evcharger.common.config.FactoryDomain;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.enums.PileVersionEnum;
import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.common.utils.StringUtil;
import com.rc.evcharger.common.utils.YlDataUtil;
import com.rc.evcharger.mapper.elec.ElecGunMapper;
import com.rc.evcharger.mapper.elec.ElecPileMapper;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecGunExample;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.elec.ElecPileExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by sven on 2019/09/23.
 */
@Service
public class ElecPileServiceImpl implements ElecPileService {

    final int RUTA_FRAME_LENGTH = 3 * 7 - 1;

    @Autowired
    private ElecPileMapper elecPileMapper;

    @Autowired
    private ElecGunMapper elecGunMapper;

    @Autowired
    private FactoryDomain factoryDomain;

    @Override
    public ElecPileMapper getMapper() {
        return elecPileMapper;
    }

    @Override
    public ElecPile selectPileByLogicAddress(String rtua) {
        if (rtua == null) {
            return null;
        }

        //兼容瑞晨8位桩编号
        if (SocketConstant.JZ_00_00.equals(rtua.substring(0, 5))) {
            //得到瑞晨的逻辑地址
            rtua = StringUtil.jzTurnRtua(rtua);
        }

        ElecGunExample elecGunExample = new ElecGunExample();
        elecGunExample.createCriteria().andPileRutaEqualTo(rtua);
        List<ElecGun> elecGuns = elecGunMapper.selectByExample(elecGunExample);
        ElecGun elecGun = elecGuns.stream().findFirst().orElseGet(() -> null);
        if (elecGun != null) {
            return elecPileMapper.selectByPrimaryKey(elecGun.getElecPileId());
        }
        return null;

//        ElecPileExample example = new ElecPileExample();
//        example.createCriteria().andPileRtuaEqualTo(rtua);
//        example.setOrderByClause("elec_pile_id ASC");
//
//        List<ElecPile> list = elecPileMapper.selectByExample(example);
//        if (list != null && list.size() > 0) {
//            return list.get(0);
//        } else {
//            return null;
//        }
    }


    @Override
    public ElecPile selectByPileNo(String pileNo) {
        String pileRuta = YlDataUtil.getTerminalIdFrame(pileNo);
        ElecGunExample example = new ElecGunExample();
        example.createCriteria().andPileRutaEqualTo(pileRuta);

        ElecGun elecGun = elecGunMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
        if (elecGun != null) {
            return elecPileMapper.selectByPrimaryKey(elecGun.getElecPileId());
        }

        return null;
//        if (pileNo == null) {
//            return null;
//        }
//
//        ElecPileExample example = new ElecPileExample();
//        example.createCriteria().andPileNoEqualTo(pileNo);
//        example.setOrderByClause("elec_pile_id ASC");
//
//        List<ElecPile> list = elecPileMapper.selectByExample(example);
//        if (list != null && list.size() > 0) {
//            return list.get(0);
//        } else {
//            return null;
//        }

//        return elecPileMapper.findByPileNoOrSlave(pileNo);

    }


    /**
     * 1.防止有心跳却离线
     * 2.后台强制踢下线
     *
     * @param elecPile
     * @return 0离线 1在线
     */
    @Override
    public int isLoginStatus(ElecPile elecPile) {
        if (elecPile == null) {
            return 0;
        }
        //后台强制踢下线
        if (SocketConstant.STR_CON0.equals(elecPile.getElecOffOnline())) {
            return 0;
        }
        //防止有心跳却离线 （永联除外,电桩先发心跳后登陆）
        if ((SocketConstant.CON0 == elecPile.getStatus()) && !factoryDomain.getFACTORY_YL_DOMAIN().equals(elecPile.getElecServerDomain())) {
            return 0;
        }
        ////防止有心跳却离线
        //if (SocketConstant.CON0 == elecPile.getStatus()) {
        //    return 0;
        //}
        return 1;
    }

    @Override
    public void updateGunUsing(Long pileId, Long gunId, Integer usingStatus) {
        ElecGun gun = elecGunMapper.selectByPrimaryKey(gunId);
        if (gun == null) {
            // 打印日志
            return;
        }

        //判断使用状态和设备状态不一致，则更新状态
        if (!gun.getStatus().equals(usingStatus) || gun.getNormalStatus() != SocketConstant.CON0) {
            //gun.setNormalStatus(SocketConstant.CON0);
            //gun.setStatus(usingStatus);
            //elecGunMapper.updateByPrimaryKeySelective(gun);

            ElecGun upateElecGun = new ElecGun();
            upateElecGun.setElecGunId(gun.getElecGunId());
            upateElecGun.setNormalStatus(SocketConstant.CON0);
            upateElecGun.setStatus(usingStatus);
            elecGunMapper.updateByPrimaryKeySelective(upateElecGun);
        }
    }

    @Override
    public void updatePileOffLine() {
        elecPileMapper.allPileOffLine();
    }

    @Override
    public ElecPile findByEpNo(String pileNo) {
        if (pileNo == null) {
            return null;
        }

        ElecPileExample example = new ElecPileExample();
        example.createCriteria().andPileNoEqualTo(pileNo);
        example.setOrderByClause("elec_pile_id   ASC");

        List<ElecPile> list = elecPileMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    //更新电桩版本号

    @Override
    public void updateGunNormal(Long pileId, String gunNum, Integer normalStatus) {
        ElecGunExample example = new ElecGunExample();
        example.createCriteria().andElecPileIdEqualTo(pileId);
        List<ElecGun> gunList = elecGunMapper.selectByExample(example);

        ElecGun gun = null;
        for (ElecGun g : gunList) {
            if (gunNum.endsWith(g.getGunNum())) {
                gun = g;
                break;
            }
        }

        if (gun == null) {
            // 打印日志
            return;
        }

        if (gun.getNormalStatus() == null || gun.getNormalStatus() != normalStatus) {
            //如果更新、则只更新一个字段
            ElecGun newElecGun = new ElecGun();
            newElecGun.setElecGunId(gun.getElecGunId());
            if (normalStatus == 1 || normalStatus.intValue() == 255) {
                newElecGun.setStatus(7);
            }
            newElecGun.setNormalStatus(normalStatus);
            elecGunMapper.updateByPrimaryKeySelective(newElecGun);
        }
    }

    @Override
    public void updateVersion(Long pileId, String version) {

        ElecPile elecPile = elecPileMapper.selectByPrimaryKey(pileId);

        if (!version.equals(elecPile.getProgramVersion())) {
            ElecPile newElecPile = new ElecPile();
            newElecPile.setElecPileId(elecPile.getElecPileId());
            newElecPile.setProgramVersion(version);
            elecPileMapper.updateByPrimaryKeySelective(newElecPile);
        }
    }

    @Override
    public String splitYcFrameByRuta(String pileRtua) {
        if (pileRtua.length() < RUTA_FRAME_LENGTH) {
            return "00 " + pileRtua;
        }
        return pileRtua;
    }

    /**
     * 是否是离网不跳枪程序
     *
     * @param version
     * @return
     */
    @Override
    public boolean elecpileVersionDiffer(String version) {
        if (StringUtils.isEmpty(version)) {
            return true;
        }
        //派诺101  新亚232 260
        //if ("232".equals(version) || "101".equals(version)) {
        //    return false;
        //}else if ("311".equals(version) ) {
        //    //不会添加结算定时器
        //    return false;
        //}
        //if ("260".equals(version) || "102".equals(version)) {
        //    return false;
        //}

        if (PileVersionEnum.getPileVersionEnumResult(version)) {
            return false;
        }

        return true;
    }

    public static void main(String[] args) {
        String rtua = "67 44 12 00 00 21 55";
        if (rtua.length() > (3 * 6 - 1)) {
            rtua = rtua.substring(0, 3 * 6 - 1);
        }
        System.out.println(rtua + "\n" + rtua.length());
    }
}
